// package: rewords-server-2024
// filename: xpool
// author: diogoxiang@gmail.com
// time: 2024/7/26 上午10:05

package xpool

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"rewords-server-2024/internal/model"
	"rewords-server-2024/internal/service"
	"time"
)

type Mongo struct {
	Client *mongo.Client
}

var (
	GMongo *Mongo
)

// InitMongo 初始化MongoDB
func InitMongo() {
	var (
		client    *mongo.Client
		mongoConf *model.MongoConf
		ctx       context.Context
		err       error
	)
	mongoConf, err = service.SysConfig().GetMongoConfig(ctx)
	if err != nil {
		panic(err)
	}
	ctx, _ = context.WithTimeout(context.TODO(), time.Duration(mongoConf.ConnectTimeout)*time.Millisecond)

	// 建立mongodb连接
	g.Log().Info(ctx, "GMongo 建立mongodb连接")
	if client, err = mongo.Connect(
		ctx,
		options.Client().ApplyURI(mongoConf.Uri)); err != nil {
		g.Log().Info(ctx, "链接 MongoDB 失败：", err)
		return
	}
	//glog.Info("建立mongodb连接 成功")
	g.Log().Info(ctx, "GMongo 建立mongodb连接 成功")

	GMongo = &Mongo{Client: client}
	return
}
